<?php

namespace app\controller\api;

use app\exception\ErrnoPlus;
use app\service\AccountService;
use app\validate\UserValidate;
use share\controller\ApiBaseController;
use share\exception\ApiException;
use share\service\CaptchaService;
use share\service\ContextService;
use share\service\QrcodeService;
use share\service\UserAuthService;
use share\service\UserBaseService;
use share\service\UserBindService;
use share\service\UserPassService;
use share\utils\Helper;

class UserController extends ApiBaseController
{

    protected $beforeActionList = [
        "checkSign" => [
            'except' => [
                'send_device_password',
                'send_device_password_v2',
                'del_by_pswd',
            ],
        ],
        "checkUser" => [
            'except' => [
                'del_by_pswd',
            ],
        ],
    ];

    /**
     * @description: 
     * @return {*}
     * @use: 
     */
    public function initValidate()
    {
        $this->validate = new UserValidate();
    }

    /**
     * 账号修改code
     */
    public function change_account_code_action()
    {
        $input = $this->check();
        if ($input["language"] === "CN" || $input["language"] === "HK" || $input["language"] === "MO" || $input["language"] === "TW") {
            $input['language'] = "zh-CN";
            $input['appName'] = "云智AI";
        } else {
            $input['language'] = "en-US";
            $input['appName'] = "MEEYE";
        }
        $userInfo = ContextService::getUserInfo();
        if ($input['userAccount'] !== $userInfo['phone'] && $input['userAccount'] !== $userInfo['email']) {
            throw new ApiException("origin account is error", ErrnoPlus::ORIGINAL_ACCOUNT_ERROR);
        }
        $input['packageName'] = ContextService::getPackageName();
        return self::ok($this->doChangeAccountCode($input));
    }

    /**
     * 账号修改
     */
    public function change_account_action()
    {
        $input = $this->check();
        $language = $input['language'];
        if ($language == "CN") {
            $input['language'] = "zh-CN";
            $input['appName'] = "云智AI";
        } else {
            $input['language'] = "en-US";
            $input['appName'] = "MEEYE";
        }
        $userInfo = ContextService::getUserInfo();
        if ($input['userAccount'] !== $userInfo['phone'] && $input['userAccount'] !== $userInfo['email']) {
            throw new ApiException("origin account is error", ErrnoPlus::ORIGINAL_ACCOUNT_ERROR);
        }
        $input['packageName'] = ContextService::getPackageName();
        return self::ok($this->doChangeAccount($input));
    }

    /**
     * 修改用户基础信息
     */
    public function update_action()
    {
        $input = $this->check();
        if (isset($input['nickName'])) {
            $input['nickName'] = Helper::filterEmoji($input['nickName']);
            if (empty($input['nickName'])) {
                throw new ApiException("nickName format error", ErrnoPlus::PARAM_ERROR);
            }
        }
        $input['vendor'] = ContextService::getVendor();
        $res = AccountService::updateBaseInfo($input, ContextService::getUserInfo());
        return self::ok($res);
    }

    /**
     * 用户注销
     */
    public function delete_action()
    {
        $input = $this->check();
        $input['vendor'] = ContextService::getVendor();
        $res = AccountService::deleteBaseInfo($input, ContextService::getUserInfo());
        return self::ok($res);
    }

    /**
     * 用户注销 google 销户平台
     */
    public function del_by_pswd_action()
    {
        $input = $this->check();
        $hash = $input['hash'];
        $code = $input['captcha'];
        $account = $input['name'];
        $password = $input['password'];
        $refer = $input['refer'];
        $vendor = self::getVendorByRefer($refer);
        if (empty($vendor)) {
            return self::fail("vendor error", ErrnoPlus::PARAM_ERROR);
        }
        if (!CaptchaController::checkHash($hash)) {
            return self::fail("hash data error", ErrnoPlus::PARAM_ERROR);
        }
        if (!CaptchaService::check($hash, $code)) {
            return self::fail("captcha error", ErrnoPlus::INVALID_PARAM);
        }
        $filter = [
            'vendor' => $vendor,
        ];
        $isEmail = strstr($account, '@');
        $user = $isEmail ? UserBaseService::getByEmail($account, $filter) : UserBaseService::getByPhone($account, $filter);
        if (empty($user)) {
            return self::fail("username or password error", ErrnoPlus::PARAM_ERROR);
        }
        if (!UserPassService::comparePass($password, $user['id'])) {
            return self::fail("username or password error", ErrnoPlus::PARAM_ERROR);
        }
        $res = AccountService::deleteBaseInfo([
            'vendor' => $vendor,
            'deleteTime' => time(),
        ], $user);
        return self::ok($res);
    }

    /**
     * 从URL中获取vendor
     */
    public static function getVendorByRefer($refer)
    {
        $domain = parse_url($refer, PHP_URL_HOST);
        $prefix = explode('.', $domain)[0];
        $prefix = strtoupper($prefix);
        $res = "";
        //	http://seeeasy.icloud-platform.net
        // 	http://seeeasy20.icloud-platform.net
        if ($prefix === "SEEEASY" || $prefix === "SEEEASY20") {
            $res = "ENZ";
        }
        // 	http://lecooit.icloud-platform.net
        else if ($prefix === "LECOOIT") {
            $res = "HDT-LENOVO";
        }
        // 	http://starling.icloud-platform.net
        else if ($prefix === "STARLING") {
            $res = "HDT-SECUREYE";
        }
        // 	http://turbocloud.icloud-platform.net
        else if ($prefix === "TURBOCLOUD") {
            $res = "HDT-SECUREYE";
        }
        // 	http://knowledge.icloud-platform.net
        else if ($prefix === "KNOWLEDGE") {
            $res = "HDT-SECUREYE";
        }
        // 	http://aeriqs.icloud-platform.net
        else if ($prefix === "AERIQS") {
            $res = "HDT-AERIQS";
        }
        // 	http://mp6200lite.icloud-platform.net
        else if ($prefix === "MP6200LITE") {
            $res = "HDT-MP6200PRO";
        }
        // 	http://secview.icloud-platform.net
        else if ($prefix === "SECVIEW") {
            $res = "SECVIEW";
        }
        // 	http://kylasight.icloud-platform.net
        else if ($prefix === "KYLASIGHT") {
            $res = "HDT-KUAIJIEDA";
        }
        // 	http://asvision.icloud-platform.net
        else if ($prefix === "ASVISION") {
            $res = "HDT-AOVISION";
        }
        // 	http://prizoreye.icloud-platform.net
        else if ($prefix === "PRIZOREYE") {
            $res = "HDT-PRIZOREYE";
        }
        // 	http://ssvms.icloud-platform.net
        else if ($prefix === "SSVMS") {
            $res = "HDT-SSVMS";
        }
        // 	http://startups.icloud-platform.net
        else if ($prefix === "STARTUPS") {
            $res = "HDT-STARTUPS";
        }
        // 	http://truecloud.icloud-platform.net
        else if ($prefix === "TRUECLOUD") {
            $res = "HDT-TRUECLOUD";
        }
        // 	http://sayvision.icloud-platform.net
        else if ($prefix === "SAYVISION") {
            $res = "HDT-SAYVISION";
        }
        // 	http://amnafarin.icloud-platform.net
        else if ($prefix === "AMNAFARIN") {
            $res = "HDT-AMNAFARIN";
        }
        // 	http://seeeasytv.icloud-platform.net/
        else if ($prefix === "SEEEASYTV") {
            $res = "ENZ";
        }
        // |BT-Connect|HDT-BTCONNECT|http://btconnect.icloud-platform.net|
        // 	http://btconnect.icloud-platform.net/
        else if ($prefix === "BTCONNECT") {
            $res = "HDT-BTCONNECT";
        }
        return $res;
    }

    /**
     * 修改密码
     */
    public function change_pswd_action()
    {
        $input = $this->check();
        $res = AccountService::changePassword($input, ContextService::getUserInfo());
        return self::ok($res);
    }

    /**
     * 搜索账号
     */
    public function search_account_action()
    {
        $input = $this->check();
        $res = AccountService::searchAccount($input);
        if (empty($res)) {
            return self::fail("no data", ErrnoPlus::NOT_BACK_DATA);
        }
        $resp = [];
        if ($res) {
            foreach ($res as $item) {
                if ($item['email']) {
                    $resp[] = $item['email'];
                }
                if ($item['phone']) {
                    $resp[] = $item['phone'];
                }
            }
            $resp = Helper::arraySmartUnique($resp);
        }
        return self::ok($resp);
    }

    /**
     * 获取搜索账号的id信息
     */
    public function account_base_info_action()
    {
        $input = $this->check();
        $res = AccountService::accountBaseInfo($input);
        if ($res) {
            $resp = [
                "userId" => $res['user_id'],
                "identityId" => $res['identity_id'],
            ];
            return self::ok($resp);
        } else {
            return self::fail("account user is not exists", ErrnoPlus::USER_NOT_EXISTS);
        }
    }

    /**
     * 发送设备临时密码
     */
    public function send_device_password_action()
    {
        $input = $this->check();
        if ($input['isoCode'] === 'CN') {
            $input['language'] = 'zh-CN';
        } else {
            $input['language'] = 'en-US';
        }
        $account = $this->doSendDevicePassword($input);
        $res = [
            'showMessage' => "请在 " . self::getMaskAccount($account) . " 上查看临时密码",
        ];
        return self::ok($res);
    }

    /**
     * 发送设备临时密码
     */
    public function send_device_password_v2_action()
    {
        $input = $this->check();
        $account = $this->doSendDevicePassword($input);
        $res = [
            'showMessage' => "请在 " . self::getMaskAccount($account) . " 上查看临时密码",
        ];
        return self::ok($res);
    }

    /**
     * 通过授权code 绑定存在的账户
     */
    public function bind_by_code_action()
    {
        $input = $this->check();
        UserAuthService::checkLoginType($input['loginType']);
        $input['appId'] = $this->request->param('appId');
        $res = AccountService::bindByCode($input, ContextService::getVendor(), ContextService::getUserInfo());
        return self::ok($res);
    }

    /**
     * 解绑第三方账号
     */
    public function unbind_action()
    {
        $input = $this->check();
        UserAuthService::checkLoginType($input['loginType']);
        $res = AccountService::unbind($input, ContextService::getUserInfo());
        return self::ok($res);
    }

    /**
     * 查询第三方账号绑定情况
     */
    public function get_bind_state_action()
    {
        $this->check();
        $userInfo = ContextService::getUserInfo();
        $bindUsers = UserBindService::getAllByFilter(['uid' => $userInfo['id']]);
        $isWechatBind = 0;
        $isAppleBind = 0;
        foreach ($bindUsers as $bind) {
            if ($bind['open_type'] == UserBindService::OPEN_TYPE_OF_WECHAT) {
                $isWechatBind = 1;
            }
            if ($bind['open_type'] == UserBindService::OPEN_TYPE_OF_APPLE) {
                $isAppleBind = 1;
            }
        }
        $res = [
            'wechat' => $isWechatBind,
            'apple' => $isAppleBind,
        ];
        return self::ok($res);
    }

    /**
     * 授权给二维码登录
     */
    public function authorize_qrcode_action()
    {
        $input = $this->check();
        $userInfo = ContextService::getUserInfo();
        $token = $input['qrcode'];
        $authInfo = UserAuthService::doAuth($userInfo);
        $res = QrcodeService::fill($token, $authInfo, $userInfo);
        if (empty($res)) {
            return self::ok([
                'token' => $token,
                'status' => 0,
            ]);
        }
        return self::ok($res);
    }

    protected function doSendDevicePassword($input)
    {
        $account = isset($input['phone']) && !empty($input['phone']) ? $input['phone'] : (isset($input['email']) ? $input['email'] : '');
        $ip = ContextService::getIP();
        $input['vendor'] = ContextService::getVendor();
        if (empty($account)) {
            throw new ApiException("lost phone or email info", ErrnoPlus::PARAM_ERROR);
        }
        if (strpos($account, '@') !== false) { //邮箱获取验证码
            if (!Helper::checkEmailFormat($account)) {
                throw new ApiException("email format error", ErrnoPlus::EMAIL_FORMAT);
            }
            AccountService::sendDevicePasswordByEmail($account, $input, ContextService::getVendor(), ContextService::getPackageName());
        } else { //短信获取
            if ($input['language'] === 'zh-CN') {
                if (!Helper::checkChinaPhone($account)) {
                    throw new ApiException("phone format error", ErrnoPlus::PHONE_FORMAT);
                }
            }
            AccountService::sendDevicePasswordByPhone($account, $input, $ip, ContextService::getVendor(), ContextService::getPackageName());
        }
        return $account;
    }


    protected function doChangeAccountCode($input)
    {
        $ip = ContextService::getIp();
        $newAccount = $input['changeAccount'];
        if (strpos($newAccount, '@') !== false) { //邮箱获取验证码
            if (!Helper::checkEmailFormat($newAccount)) {
                throw new ApiException("email format error", ErrnoPlus::EMAIL_FORMAT);
            }
            $data = AccountService::sendChangeAccountCodeByEmail($newAccount, $input, ContextService::getVendor(), ContextService::getPackageName());
        } else { //短信获取
            if (isset($input['language']) && $input['language'] === 'zh-CN') {
                if (!Helper::checkChinaPhone($newAccount)) {
                    throw new ApiException("phone format error", ErrnoPlus::PHONE_FORMAT);
                }
            }
            $data = AccountService::sendChangeAccountCodeByPhone($newAccount, $input, $ip, ContextService::getVendor(), ContextService::getPackageName());
        }
        return $data;
    }


    protected function doChangeAccount($input)
    {
        $ip = ContextService::getIp();
        $newAccount = $input['changeAccount'];
        if (strpos($newAccount, '@') !== false) { //邮箱获取验证码
            if (!Helper::checkEmailFormat($newAccount)) {
                throw new ApiException("email format error", ErrnoPlus::EMAIL_FORMAT);
            }
            $data = AccountService::changeAccountByEmail($newAccount, $input, ContextService::getVendor(), ContextService::getPackageName());
        } else { //短信获取
            if (isset($input['language']) && $input['language'] === 'zh-CN') {
                if (!Helper::checkChinaPhone($newAccount)) {
                    throw new ApiException("phone format error", ErrnoPlus::PHONE_FORMAT);
                }
            }
            $data = AccountService::changeAccountByPhone($newAccount, $input, $ip, ContextService::getVendor(), ContextService::getPackageName());
        }
        return $data;
    }

    public static function getMaskAccount($account)
    {
        $pos = strpos($account, '@');
        if ($pos) {
            return substr($account, 0, min($pos, 4)) . "***" . substr($account, $pos);
        } else {
            return substr($account, 0, 3) . "***" . substr($account, -4);
        }
    }
}
